﻿using System;
using System.Web;
using EPiServer;
using EPiServer.Core;
using EPiServer.Web;
using TemplateFoundation.Core;
using TemplateFoundation.Exceptions;

namespace TemplateFoundation.Handlers
{
    /// <summary>
    /// Handles requests to permanent EPiServer links by redirecting the client to the actual friendly URL
    /// </summary>
    public class PermanentLinksHandler : IHttpHandler
    {
        #region IHttpHandler Members

        /// <summary>
        /// Gets false indicating this handler isn't reusable
        /// </summary>
        public bool IsReusable
        {
            get { return false; }
        }

        /// <summary>
        /// Enables processing of HTTP Web requests by a custom HttpHandler that implements the <see cref="T:System.Web.IHttpHandler"/> interface.
        /// </summary>
        /// <param name="context">An <see cref="T:System.Web.HttpContext"/> object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests.</param>
        public void ProcessRequest(HttpContext context)
        {
            context.Response.Clear();

            string url = context.Request.Url.LocalPath;

            if(!url.StartsWith("~"))
            {
                url = "~" + url;
            }

            if(!url.StartsWith("~/link/"))
            {
                throw new TemplateFoundationException("Permanent links handler expects the URL to start with '/link/'");
            }

            var ub = new UrlBuilder(url);

            var link = PermanentLinkUtility.FindPageReference(new Guid(url.Replace("~/link/", string.Empty)));

            if(PageReference.IsNullOrEmpty(link))
            {
                context.Response.StatusCode = 410;
                context.Response.End();
                return;
            }

            context.Response.StatusCode = 302;
            context.Response.RedirectLocation=link.GetPage().GetFriendlyUrl();
            context.Response.End();
        }

        #endregion
    }
}
